package priv.lhy.securitydemo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import priv.lhy.securitydemo.dao.AuthorityDAO;
import priv.lhy.securitydemo.dao.UserDAO;
import priv.lhy.securitydemo.entity.Authorities;
import priv.lhy.securitydemo.entity.AuthorityUser;
import priv.lhy.securitydemo.entity.Users;

import java.util.List;

/**
 * @author: lihy
 * date: 2019/10/5 9:59
 * description:
 */
@Service
public class UserService implements UserDetailsService{

    @Autowired
    private UserDAO userDAO;

    @Autowired
    private AuthorityDAO authorityDAO;

    private PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(8);


    public int addUser(Users user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return userDAO.insertUser(user);
    }

    public Users getUser(String username, String password) {
        Users user = userDAO.getUser(username);
        if (!BCrypt.checkpw(password, user.getPassword())) {user = null;}

        return user;
    }

    public int addAuthorities(List<Authorities> list) {
        return authorityDAO.insertAuthorities(list);
    }

    public Users getAuthorities(Users user) {
        List<Authorities> list = authorityDAO.getAuthorities(user.getUsername());
        user.setAuthorities(list);
        return user;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Users user = userDAO.getUser(username);
        //user.setUsername(username);
        user = getAuthorities(user);
        return new AuthorityUser(user);
    }
}
